<template>
  <div>
    姓名: <input v-model="form.name" type="text"><br>
    年龄: <input v-model="form.age" type="text"><br>
    性别:
    <select  v-model="form.gender">
      <option value="男">男</option>
      <option value="女">女</option>
    </select><br>
    <button @click="add">添加</button>
    <button @click="modify">修改</button>
    <br>
    <table border>
      <thead>
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="remove(item.id)">删除</button>&nbsp;
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [
        { id: 11, name: 'Tom', gender: '男', age: 19 },
        { id: 22, name: 'Jone', gender: '女', age: 21 },
      ],
      form: {name: '' ,age: '', gender: '', id: ''}
    }
  },
  methods: {
    add() {
      const { name, age, gender } = this.form
      if (name === '' || age === '' || gender === '') return alert('请输入数据')
      this.arr.push({
        name,
        age,
        gender,
        id: Date.now()
      })
      this.form = {
        name: '',
        age: '',
        gender: ''
      }
    },
    edit(id) {
      const str = this.arr.find(item => item.id === id)
      console.log(id)
      this.form = { ...str}
    },
    modify() {
      const i = this.form.id
      // console.log(i)
      const str = this.arr.find(item => item.id === i)
      str.name = this.form.name
      str.age = this.form.age
      str.gender = this.form.gender
      this.form = {
        name: '',
        age: '',
        gender: ''
      }
    },
    remove(id) {
      // const index = this.form.id
      // console.log(i)
      const index = this.arr.findIndex(item => item.id === id)
      this.arr.splice(index, 1)
    }
  }
}
</script>

<style scoped>
table {
  /* border: 1px solid black; */
  border-collapse: collapse;
}
td, th {
  padding: 10px;
}
</style>
